package com.ruoyi.app.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.app.service.ITrialService;
import com.ruoyi.bizsys.domain.LoanIou;
import com.ruoyi.bizsys.mapper.LoanIouMapper;
import com.ruoyi.bizsys.service.ILoanIouService;
import com.ruoyi.business.processIou.service.ProcessForIouDefferredService;
import com.ruoyi.business.service.IDoRepaymentLastService;
import com.ruoyi.business.service.IRepaymentService;
import com.ruoyi.common.enums.RspEnmu;
import com.ruoyi.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 延期还款试算
 */
@Service("deferredRepayService")
@Slf4j
public class DeferredRepayService implements ITrialService {

    @Autowired
    IRepaymentService repaymentService;
    @Autowired
    IDoRepaymentLastService doRepaymentLastService;
    @Autowired
    ILoanIouService loanIouService;
    @Autowired
    ProcessForIouDefferredService processForIouDefferredService;
    @Resource
    LoanIouMapper loanIouMapper;
    @Override
    public JSONObject handle(JSONObject params) {
        LoanIou loanIou = loanIouMapper.getLoanIouByLoanSerialNo(params.getString("loanSerialNo"));
        BigDecimal iouRepayAmt = processForIouDefferredService.getTotalAmountBy(params,loanIou);
        log.info("延期还款试算：{},{}", params.getString("loanSerialNo"), iouRepayAmt);
        // 进一步验证
        if (params.getBoolean("isJustWallet")) {
            log.info("延期还款试算:{},只用钱包还款", params.getString("loanSerialNo"));
            // 接口查询钱包是够足够,此处不冻结钱包
            BigDecimal amtWalletObj = doRepaymentLastService.getWalletAmount(loanIou.getCustNo());
            if (amtWalletObj.compareTo(iouRepayAmt) < 0) {
                log.info("延期还款试算:{},只用钱包还款钱包不够", params.getString("loanSerialNo"));
                throw new BusinessException(RspEnmu.REPAYMENT_WALLET_NOT_ENOUGH);
            }
        }
        JSONObject res = new JSONObject();
        res.put("totalAmount", iouRepayAmt);
        return res;
    }
}